import java.util.Random;
import java.util.Stack;
//Updating

public class IODevice extends Thread {

	public static int MIN_DELAY = 30;
	
	public static int MAX_DELAY = 50;
	
	private Stack<Pcb> pcb_stack;
	
	public CPU cpu1;
	
	private DeviceType device_type;

	private Random random;
	
	public IODevice(CPU cpu, DeviceType type) {
		this.pcb_stack = new Stack<Pcb>();
		this.device_type = type;
		this.random = new Random();
		this.cpu1 = cpu;
	}
	
	public DeviceType getDeviceType() {
		return device_type;
	}
	
	public void addPcb(Pcb pcb) {
		pcb_stack.push(pcb);
	}
	
	@Override
	public void run() {
		while (true) {
			int delay = random.nextInt(MAX_DELAY - MIN_DELAY + 1) + MIN_DELAY;
			try {
				Thread.sleep(delay);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			
			System.out.println(device_type.toString() + " triggered an interupt");
			
			if (pcb_stack.empty()) {
				System.out.println("No process is waiting for " + device_type.toString());
			} else {
				Pcb pcb = pcb_stack.pop();
				cpu1.IOInterrupt(pcb);
			}
			
		}
	}

	public enum DeviceType {
		DISK, KEYBOARD;
	}
	
}
